package com.brick.controller;

import com.brick.entity.Commodity;
import com.brick.entity.Result;
import com.brick.service.CommodityService;
import com.brick.util.ResultUtil;
import com.brick.util.Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequestMapping("/api/commodityServlet")
@RestController
public class CommodityController {

    @Autowired
    CommodityService commodityService;

    @RequestMapping("/getCommodity")
    public Result<List<Commodity>> getCommodity(@RequestBody Commodity commodity, BindingResult bindingResult){
        PageHelper.startPage(commodity.getPageNum(),commodity.getPageSize());
        List<Commodity> commodityList = commodityService.selectAll(commodity);

        PageInfo<Commodity> pageInfo = new PageInfo<>(commodityList);

        commodityList = pageInfo.getList();

        if (bindingResult.hasErrors()){
            return ResultUtil.error(0,bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultUtil.success(commodityList, pageInfo.getTotal());
    }

    @RequestMapping("/addCommodity")
    public Result<List<Commodity>> addCommodity(@RequestBody Commodity commodity, BindingResult bindingResult){
        commodity.setId(Util.util.getUUID());
        commodity.setDateline(Util.util.getDateNow());
        commodity.setState(1);
        if (bindingResult.hasErrors()){
            return ResultUtil.error(0,bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultUtil.success(commodityService.insert(commodity));
    }

    @RequestMapping("/updateCommodity")
    public Result<List<Commodity>> updateCommodity(@RequestBody Commodity commodity, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return ResultUtil.error(0,bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultUtil.success(commodityService.update(commodity));
    }
}
